package gui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import model.CardInterface;
import model.CardRank;
import toolkit.Debug;
import toolkit.Global;
import toolkit.Paint;
import toolkit.Parse;

public class Card extends JComponent
{
	private final CardInterface card;
	
	private Image image;
	
	private BufferedImage bufferedImage;
	
	public Card(CardInterface card)
	{
		this.card = card;
		
		// Set dimensions.
		BufferedImage bufferedImage = getBufferedImage();
		int width = bufferedImage.getWidth(), height = bufferedImage.getHeight();
		setSize(width, height);
		setPreferredSize(new Dimension(width, height));
		
		// Set tool text.
		setToolTipText(card.toString());
	}
	
	public String getImagePath()
	{
		String filename = "";
		filename += card.getSuit().toShortString();
		filename += card.getRank() != CardRank.ACE ? card.getRank().toShortString() : '1';
		
		return Global.getUserDir() + "/src/view/images/cards/" + filename + ".png";
	}
	
	public Image getImage()
	{
		if (image == null)
		{
			image = Toolkit.getDefaultToolkit().getImage(getImagePath());
		}
		
		return image;
	}
	
	public BufferedImage getBufferedImage()
	{
		if (bufferedImage == null)
		{
			bufferedImage = Paint.toBufferedImage(getImage());
		}
		
		return bufferedImage;
	}
	
	public void paintComponent(Graphics g)
	{
		Paint paint = new Paint(g);
		
		Graphics2D g2 = paint.newLayer();
		
		double scaleX = (double) getWidth() / bufferedImage.getWidth();
		double scaleY = (double) getHeight() / bufferedImage.getHeight();

		g2.drawRenderedImage(bufferedImage, AffineTransform.getScaleInstance(scaleX, scaleY));
		g2.dispose();
	}
	
	public String toString()
	{
		return card.toString();
	}
}
